package cn.com.ry.framework.linklog.okhttp.filter;

import cn.com.ry.framework.linklog.constant.LinkLogConstants;
import cn.com.ry.framework.linklog.context.LinkLogContext;
import cn.com.ry.framework.linklog.context.SpanIdGenerator;
import cn.com.ry.framework.linklog.util.HostInfo;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class LinkLogOkHttpInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(LinkLogOkHttpInterceptor.class);

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request requestFu = null;
        try {
            //拿到request
            requestFu = chain.request();
            //用request获取网址
            String url = requestFu.url().toString();
            if (url != null && !url.trim().equalsIgnoreCase("")) {
                //1.判断上下文有没有 traceId
                String traceId = LinkLogContext.getTraceId();
                if (traceId != null && !traceId.equals("")) {
                    Request.Builder builder = requestFu.newBuilder();
                    Request build = builder.url(url).build();
                    String preApp = HostInfo.getAppName();
                    String preHost = HostInfo.getHostName();
                    String preIp = HostInfo.getIp();
                    String spanId = SpanIdGenerator.generateNextSpanId();
                    builder.addHeader(LinkLogConstants.LINKLOG_PRE_APP_KEY, preApp);
                    builder.addHeader(LinkLogConstants.LINKLOG_PRE_HOST_KEY, preHost);
                    builder.addHeader(LinkLogConstants.LINKLOG_PRE_IP_KEY, preIp);
                    builder.addHeader(LinkLogConstants.LINKLOG_TRACE_KEY, traceId);
                    builder.addHeader(LinkLogConstants.LINKLOG_SPANID_KEY, spanId);
                    return chain.proceed(build);
                } else {
                    logger.debug("[LinkLog]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
                }
            }
        } catch (Exception e) {
        }

        if (requestFu != null) {
            return chain.proceed(requestFu);
        }
        return null;
    }
}
